/*
 * Licensed to the Apache Software Foundation (ASF) under one
 * or more contributor license agreements.  See the NOTICE file
 * distributed with this work for additional information
 * regarding copyright ownership.  The ASF licenses this file
 * to you under the Apache License, Version 2.0 (the
 * "License"); you may not use this file except in compliance
 * with the License.  You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.zx.learn.flink.official.frauddetection;

import com.zx.learn.flink.official.frauddetection.entity.Alert;
import com.zx.learn.flink.official.frauddetection.entity.Transaction;
import com.zx.learn.flink.official.frauddetection.sink.AlertSink;
import com.zx.learn.flink.official.frauddetection.source.TransactionSource;
import org.apache.flink.streaming.api.datastream.DataStream;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;

/**
 * Skeleton code for the datastream walkthrough
 * 定义了程序的数据流
 */
public class FraudDetectionJob {
    public static void main(String[] args) throws Exception {
        //设置你的执行环境。 任务执行环境用于定义任务的属性、创建数据源以及最终启动任务的执行。
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();

        //创建数据源
        //数据源从外部系统例如 Apache Kafka、Rabbit MQ 或者 Apache Pulsar 接收数据，然后将数据送到 Flink 程序中。
        DataStream<Transaction> transactions = env
                .addSource(new TransactionSource())
                .name("transactions");

        //对事件分区 & 欺诈检测
        DataStream<Alert> alerts = transactions
                //为了保证同一个 task 处理同一个 key 的所有数据，你可以使用 DataStream#keyBy 对流进行分区。欺诈行为的发生是基于某一个账户的
                .keyBy(Transaction::getAccountId)
                //对流绑定了一个操作，这个操作将会对流上的每一个消息调用所定义好的函数。
                .process(new FraudDetector())
                .name("fraud-detector");

        //sink 会将 DataStream 写出到外部系统
        alerts
                // AlertSink 使用 INFO 的日志级别打印每一个 Alert 的数据记录，而不是将其写入持久存储，以便你可以方便地查看结果。
                .addSink(new AlertSink())
                .name("send-alerts");

        //Flink 程序是懒加载的，并且只有在完全搭建好之后，才能够发布到集群上执行。
        // 调用 StreamExecutionEnvironment#execute 时给任务传递一个任务名参数，就可以开始运行任务。
        env.execute("Fraud Detection");
    }
}
